<?php
if (php_sapi_name () != 'cli' || ! empty ( $_SERVER ['REMOTE_ADDR'] )) {
	echo "Access denied";
	
	exit ();
}

define ( "SITE_PATH", dirname ( __FILE__ ) );
// подключение ядра
include_once SITE_PATH . "/include/core.php";

set_time_limit ( 0 );

// ведение лога
$_LOG = "Запуск парсера - " . date ( "d.m.Y H:i" ) . "\n";
echo $_LOG;

$tStart = get_sec ();
$_NOW = mktime ( date ( "H" ), date ( "i" ), date ( "s" ), date ( "m" ), date ( "d" ), date ( "Y" ) );
Parser_Search ();

$_LOG .= "Всего времени ушло: " . (get_sec () - $tStart) . " сек\n";
echo "Всего времени ушло: " . (get_sec () - $tStart) . " сек\n";
$_LOG .= "----------------------------------\n";

$fLOG = fopen ( SITE_PATH . "/log_" . date ( "Y-m-d" ) . ".txt", 'a' );
fwrite ( $fLOG, $_LOG );
fclose ( $fLOG );

// парсер страницы поиска
function Parser_Search() {
	global $_Tpl, $_LOG;
	// определение страницы
	$_URL = new URL ();
	for($i = 1; $i < 20; $i ++) {
		// загрузка страницы
		$_HTML = "";
		$_HTML = $_URL->GET ( "http://suchen.mobile.de/fahrzeuge/searchresults.html?pageNumber=" . $i . "&scopeId=C&sortOption.sortBy=creationTime&sortOption.sortOrder=DESCENDING&damageUnrepaired=ALSO_DAMAGE_UNREPAIRED&export=ALSO_EXPORT&lang=ru" );
		if (! $_HTML) {
			$_LOG .= "** Ошибка загрузки " . $i . " страницы\n";
			echo "** Ошибка загрузки " . $i . " страницы\n";
			return 0;
		} else {
			$_LOG .= "-- Страница - " . $i . "\n";
			echo "-- Страница - " . $i . "\n";
		}
		// выбор куска с описанием машин   
		preg_match ( "#<form action=\"\" name=\"parkAndCompareVehicle\" id=\"parkAndCompareVehicle\">(.+?)<\/form>#si", $_HTML, $matchArr );
		// запуск функции прохода  
		$bAdd = Parser_AllCars ( $matchArr [0] );
	
		// проверка
	//if ($bAdd == 2) {return 0;}
	//elseif ($bAdd == 0) {$_LOG .= "** Ошибка обработки машин\n"; return 0;}
	}
	return 0;
}
function Parser_AllCars(&$_HTML) {
	global $_MYSQL, $_LOG, $_NOW;
	$_URL = new URL ();
	$_Page = new Parser ( $_HTML );
	// проход по всем авто
	$tArr = $_Page->GET ( "strong a.detailsViewLink" )->toArr ();
	$tArrS = $_Page->GET ( "div.priceBoxWrapper div.online-since" )->toArr ();
	for($i = 0, $j = 0; $i < $tArr ["childs"] ["length"]; $i ++) {
		if ($tArr ["childs"] [$i] ["text"] == "") {
			continue;
		}
		// проверка даты добавления объявления
		$osince = $tArrS ["childs"] [$j] ["text"];
		$j ++;
		preg_match ( "#([0-9]+).([0-9]+).([0-9]+) ([0-9]+):([0-9]+)#usi", $osince, $matchArr );
		$tNow = mktime ( $matchArr [4], $matchArr [5], "0", $matchArr [2], $matchArr [1], $matchArr [3] );
		//if (($_NOW - $tNow) > 3600) {return 2;}
		// парсинг
		$tStart = get_sec ();
		$carDetails = array ();
		$info = $tArr ["childs"] [$i];
		$carDetails ["car"] ["car-date_add"] = $matchArr [3] . '-' . $matchArr [2] . '-' . $matchArr [1] . ' ' . $matchArr [4] . ':' . $matchArr [5] . ":00";
		// id машины на mobile.de
		preg_match ( "#\?id=(.+?)&#uis", $info ["href"], $matchArr );
		$carDetails ["car"] ["car-mobile-id"] = str_replace ( "f", "", $matchArr [1] );
		// поиск в бд машины с таким id
		$_SELECT = $_MYSQL->SELECT ( "SELECT `car-id` FROM `{p}cars` WHERE `car-mobile-id` = " . $carDetails ["car"] ["car-mobile-id"] );
		$_LOG .= "---- машина " . $carDetails ["car"] ["car-mobile-id"] . ": ";
		echo "---- машина " . $carDetails ["car"] ["car-mobile-id"] . ": ";
		// если нет - копирование с mobile.de
		if (! $_SELECT) {
			$_LOG .= "добавление";
			echo "добавление";
			// обработка
			# цена, информация о дилере
			$tLStart = get_sec ();
			$_HTML = $_URL->GET ( "http://suchen.mobile.de/fahrzeuge/showDetails.html?id=" . $carDetails ["car"] ["car-mobile-id"] . "&tabNumber=1&lang=ru" );
			if (! $_HTML) {
				$_LOG .= "\n** Ошибка загругзки (цена, дилер)\n";
				echo "\n** Ошибка загругзки (цена, дилер)\n";
				return FALSE;
			}
			Parse_CarPrice ( $_HTML, $carDetails );
			$_LOG .= ", цена/диллер(" . (get_sec () - $tLStart) . ")";
			echo ", цена/диллер(" . (get_sec () - $tLStart) . ")";
			# изображения
			$tLStart = get_sec ();
			$_HTML = $_URL->GET ( "http://suchen.mobile.de/fahrzeuge/showDetails.html?id=" . $carDetails ["car"] ["car-mobile-id"] . "&tabNumber=2&lang=ru" );
			if (! $_HTML) {
				$_LOG .= "\n** Ошибка загругзки (изображения)\n";
				echo "\n** Ошибка загругзки (изображения)\n";
				return FALSE;
			}
			Parse_CarImages ( $_HTML, $carDetails );
			$_LOG .= ", изображения(" . (get_sec () - $tLStart) . ")";
			# характеристики
			$tLStart = get_sec ();
			$_HTML = $_URL->GET ( "http://suchen.mobile.de/fahrzeuge/showDetails.html?id=" . $carDetails ["car"] ["car-mobile-id"] . "&tabNumber=3&lang=ru" );
			if (! $_HTML) {
				$_LOG .= "\n** Ошибка загругзки (хар-ка)\n";
				return FALSE;
			}
			Parse_CarDetails ( $_HTML, $carDetails );
			$_LOG .= ", хар-ки(" . (get_sec () - $tLStart) . ")";
			// сохранение в БД
			$bAdd = Car_Save ( $carDetails );
			if (! $bAdd) {
				$_LOG .= "\n** Ошибка добавления в БД\n";
			} else {
				$_LOG .= ", бд. ";
			}
		} else {
			$_LOG .= "уже есть в БД. ";
		}
		$_LOG .= "Время: " . ($tStart - get_sec ()) . "\n";
	}
	return TRUE;
}
// парсинг страницы (цена и инфо. о дилере)
function Parse_CarPrice(&$_HTML, &$carDetails) {
	$_Page = new Parser ( $_HTML );
	// цена
	$tArr = $_Page->GET ( "div#priceBox" )->toArr ();
	for($i = 0; $i < $tArr ["childs"] ["length"]; $i ++) {
		$price = $tArr ["childs"] [$i];
		// брутто
		if (mb_stripos ( $price ["text"], "брутто" ) !== FALSE) {
			if ($carDetails ["price"] ["p-price"] != "") {
				continue;
			}
			preg_match_all ( "#[0-9]+#usi", $price ["text"], $matchArr );
			if (! $matchArr [0]) {
				continue;
			}
			foreach ( $matchArr [0] as $m ) {
				$carDetails ["price"] ["p-price"] .= $m;
			}
			if (mb_stripos ( $price ["text"], "EUR" )) {
				$carDetails ["price"] ["p-price-cur"] = "EUR";
			}
			if (mb_stripos ( $price ["text"], "PLN" )) {
				$carDetails ["price"] ["p-price-cur"] = "PLN";
			}
			$carDetails ["price"] ["p-brutto"] = 1;
		} else if (mb_stripos ( $price ["text"], "нетто" ) !== FALSE) { //нетто
			if ($carDetails ["price"] ["p-netto"] != "") {
				continue;
			}
			preg_match_all ( "#[0-9]+#usi", $price ["text"], $matchArr );
			if (! $matchArr [0]) {
				continue;
			}
			foreach ( $matchArr [0] as $m ) {
				$carDetails ["price"] ["p-netto"] .= $m;
			}
			if (mb_stripos ( $price ["text"], "EUR" )) {
				$carDetails ["price"] ["p-netto-cur"] = "EUR";
			}
			if (mb_stripos ( $price ["text"], "PLN" )) {
				$carDetails ["price"] ["p-netto-cur"] = "PLN";
			}
		} elseif (mb_strpos ( $price ["text"], "НДС не возвращается" ) !== FALSE) {
			$carDetails ["price"] ["p-nds-recov"] = 0;
		} elseif (mb_strpos ( $price ["text"], "НДС" ) !== FALSE) {
			$carDetails ["price"] ["p-nds-recov"] = 1;
			$carDetails ["price"] ["p-nds"] = $price ["text"];
		} elseif (mb_strpos ( $price ["text"], "Торг" ) !== FALSE) {
			$carDetails ["price"] ["p-torg"] = 1;
		} else {
			preg_match_all ( "#[0-9]+#usi", $price ["text"], $matchArr );
			if ($matchArr [0]) {
				$carDetails ["price"] ["p-price"] = "";
				foreach ( $matchArr [0] as $m ) {
					$carDetails ["price"] ["p-price"] .= $m;
				}
			}
			if (mb_strpos ( $price ["text"], "EUR" )) {
				$carDetails ["price"] ["p-price-cur"] = "EUR";
			}
			if (mb_strpos ( $price ["text"], "PLN" )) {
				$carDetails ["price"] ["p-price-cur"] = "PLN";
			}
		}
	}
	// диллер
	$tArr = $_Page->GET ( "div.detailbox h3" )->toArr ();
	$carDetails ["diler"] ["di-type"] = $tArr ["childs"] [$tArr ["childs"] ["length"] - 1] ["text"];
	$_Page = $_Page->GET ( "div.dealer-contact-data" );
	$tArr = $_Page->GET ( "a.companyName" )->toArr ();
	$carDetails ["diler"] ["di-name"] = $tArr ["text"];
	$carDetails ["diler"] ["di-href"] = $tArr ["href"];
	$tArr = $_Page->GET ( "div.dealer-contact-data div.detailtext" )->toXML ();
	preg_match ( "#<div class=\"detailtext\">(.+?)<\/div>#usi", $tArr, $matchArr );
	$carDetails ["diler"] ["di-info"] = $matchArr [1];
}
// парсинг изображений
function Parse_CarImages(&$_HTML, &$carDetails) {
	$_Page = new Parser ( $_HTML );
	$tArr = $_Page->GET ( "a.img" )->toArr ();
	for($i = 0; $i < $tArr ["childs"] ["length"]; $i ++) {
		$img = $tArr ["childs"] [$i];
		$tmp = array ();
		if (mb_strpos ( $img ["rel"], "icon_video.gif" ) !== FALSE || mb_strpos ( $img ["childs"] [0] ["src"], "icon_video.gif" ) !== FALSE) {
			continue;
		}
		$tmp ["i-full"] = $img ["rel"];
		$tmp ["i-thumb"] = $img ["childs"] [0] ["src"];
		$carDetails ["imgs"] [] = $tmp;
	}
	if (! $carDetails ["imgs"] && mb_strpos ( $tArr ["src"], "icon_video.gif" ) == FALSE) {
		$tArr = $_Page->GET ( "img#currentImage" )->toArr ();
		if ($tArr ["src"]) {
			$carDetails ["imgs"] [0] ["i-full"] = $tArr ["src"];
			$carDetails ["imgs"] [0] ["i-thumb"] = $tArr ["src"];
		}
	}
}
// парсер страницы характеристик
function Parse_CarDetails(&$page, &$carDetails) {
	global $_Lang;
	$_HTML = new Parser ( $page );
	// название
	$tArr = $_HTML->get ( "div.headline h1" )->toArr ();
	$carDetails ["car"] ["car-name"] = str_replace ( array ('\'', '\"' ), "", $tArr ["text"] );
	// определение типа машины
	$tArr = $_HTML->GET ( "strong.overview-tab-headline" )->toArr ();
	foreach ( $_Lang->car as $o => $v ) {
		if (mb_stripos ( $tArr ["text"], $v ) !== FALSE) {
			$carDetails ["car"] ["car-type"] = $o;
			break;
		}
	}
	// поврежденное тс
	if (mb_stripos ( $tArr ["text"], "поврежденное" ) !== FALSE) {
		$carDetails ["car"] ["car-damaged"] = 1;
	}
	// поддержаный/новый
	if (mb_stripos ( $tArr ["text"], "Новый" ) !== FALSE) {
		$carDetails ["car"] ["car-new"] = 1;
	}
	// характеристики
	$_ELEM = $_HTML->get ( "div.vehicleFeatures" );
	$TermsArr = $_ELEM->get ( "div.vehicleFeatures dl.feature-pairs dt.term" )->toArr ();
	$ValuesArr = $_ELEM->get ( "div.vehicleFeatures dl.feature-pairs dd.value" )->toArr ();
	$iT = $TermsArr ["childs"] ["length"] - 1;
	$iV = $ValuesArr ["childs"] ["length"] - 1;
	for(; $iV >= 0; $iV --, $iT --) {
		$term = $TermsArr ["childs"] [$iT] ["text"];
		$value = $ValuesArr ["childs"] [$iV] ["text"];
		//$term_t  = iconv("UTF-8", "WINDOWS-1251", $term);
		//$value_t = iconv("UTF-8", "WINDOWS-1251", $value);
		if (mb_strpos ( $term, "Первая регистрация" ) !== FALSE || (mb_strpos ( $term, "Общий осмотр" ) !== FALSE) || (mb_strpos ( $term, "Ежегодная проверка на уровень выбросов" ) !== FALSE)) {
			$d = mb_substr ( $value, - 4, 4 );
			if (mb_strlen ( $value ) > 4) {
				$d .= ('-' . mb_substr ( $value, 0, 2 ));
			} else {
				$d .= "-01";
			}
			$d .= "-01";
			if (mb_strpos ( $term, "Первая регистрация" ) !== FALSE) {
				$carDetails ["car"] ["car-freg"] = $d;
			} elseif (mb_strpos ( $term, "Общий осмотр" ) !== FALSE) {
				$carDetails ["options"] ["o-check"] = $d;
			} elseif (mb_strpos ( $term, "Ежегодная проверка на уровень выбросов" ) !== FALSE) {
				$carDetails ["options"] ["o-ever-check"] = $d;
			}
		} elseif (mb_stripos ( $term, "общий осмотр/ежегодная" ) !== FALSE) {
			$carDetails ["options"] ["o-new-check"] = $value;
		} elseif (mb_strpos ( $term, "Количество владельцев" ) !== FALSE) {
			$carDetails ["car"] ["car-n_owners"] = $value;
		} elseif (mb_strpos ( $term, "Пробег:" ) !== FALSE) {
			preg_match_all ( "/[0-9]+/msi", $value, $matchArr );
			if ($matchArr [0]) {
				foreach ( $matchArr [0] as $m ) {
					$carDetails ["car"] ["car-mileage"] .= $m;
				}
			}
		} elseif (mb_strpos ( $term, "Объем двигателя" ) !== FALSE) {
			$carDetails ["car"] ["car-eng_volume"] = $value;
		} elseif (mb_strpos ( $term, "Мощность" ) !== FALSE) {
			preg_match ( "/([0-9]+) кВт/si", $value, $matchArr );
			$carDetails ["car"] ["car-power"] = $matchArr [1];
		} elseif (mb_strpos ( $term, "Год выпуска" ) !== FALSE) {
			$carDetails ["car"] ["car-year"] = $value;
		} elseif (mb_strpos ( $term, "Тип топлива" ) !== FALSE) {
			foreach ( $_Lang->fuel as $o => $v ) {
				if (mb_strpos ( $value, $v ) !== FALSE) {
					$carDetails ["fuel"] [$o] = 1;
				}
			}
		} elseif (mb_strpos ( $term, "Коробка передач" ) !== FALSE) {
			foreach ( $_Lang->gear as $o => $v ) {
				if (mb_strpos ( $value, $v ) !== FALSE) {
					$carDetails ["car"] ["car-gearbox"] = $o;
					break;
				}
			}
		} elseif (mb_strpos ( $term, "Климатическая установка" ) !== FALSE) {
			foreach ( $_Lang->clim as $o => $v ) {
				if (mb_strpos ( $value, $v ) !== FALSE) {
					$carDetails ["car"] ["car-climat-contr"] = $o;
					break;
				}
			}
		} elseif (mb_strpos ( $term, "Число мест" ) !== FALSE) {
			$carDetails ["car"] ["car-n_seats"] = $value;
		} elseif (mb_strpos ( $term, "Число дверей" ) !== FALSE) {
			preg_match ( "/([0-9]{1})\//", $value, $matchArr );
			$carDetails ["car"] ["car-n_dors"] = $matchArr [1];
		} elseif (mb_strpos ( $term, "Тип отделки" ) !== FALSE) {
			foreach ( $_Lang->decor as $o => $v ) {
				if (mb_stripos ( $value, $v ) !== FALSE) {
					$carDetails ["decors"] [$o] = 1;
				}
			}
		} elseif (mb_strpos ( $term, "Цвет отделки" ) !== FALSE) {
			foreach ( $_Lang->d_color as $o => $v ) {
				if (mb_stripos ( $value, $v ) !== FALSE) {
					$carDetails ["decors"] [$o] = 1;
				}
			}
		} elseif (mb_strpos ( $term, "Комбинированный уровень CO2" ) !== FALSE) {
			$carDetails ["car"] ["car-co2_comb"] = $value;
		} elseif (mb_strpos ( $term, "Расход топлива (загородный)" ) !== FALSE) {
			$carDetails ["car"] ["car-fuel_rcountry"] = $value;
		} elseif (mb_strpos ( $term, "Расход топлива (городской)" ) !== FALSE) {
			$carDetails ["car"] ["car-fuel_rcity"] = $value;
		} elseif (mb_strpos ( $term, "Расход топлива комбинированный" ) !== FALSE) {
			$carDetails ["car"] ["car-fuel_rcomb"] = $value;
		} elseif (mb_strpos ( $term, "Класс экологической безопасности" ) !== FALSE) {
			$carDetails ["car"] ["car-safe-class"] = str_replace ( "Евро", "", $value );
		} elseif (mb_strpos ( $term, "Наклейка" ) !== FALSE) {
			preg_match ( "/([0-9]{1}) \(/", $value, $matchArr );
			$carDetails ["car"] ["car-safe-label"] = $matchArr [1];
		} elseif (mb_strpos ( $term, "Цвет" ) !== FALSE) {
			foreach ( $_Lang->color as $o => $v ) {
				if (mb_stripos ( $value, $v ) !== FALSE) {
					$carDetails ["colors"] [$o] = 1;
				}
			}
		}
	}
	unset ( $TermsArr );
	unset ( $ValueArr );
	//$tArr = $_HTML->GET("div.box-content div#ad-description")->toXML();
	//preg_match("#<div id=\"ad-description\" class=\"ad-description-detail\">(.+?)<\/div>#usi", $tArr, $matchArr);
	//$carDetails["options"]["o-info"] = $matchArr[1];
	$tArr = $_HTML->GET ( "div.detailbox div.box-content" )->toArr ();
	$info = $tArr ["childs"] [0] ["text"];
	foreach ( $_Lang->optionArr as $o ) {
		if ($o == "o-airbag") {
			foreach ( $_Lang->Text [$o] as $o1 => $v ) {
				if (mb_strpos ( $info, $v ) !== FALSE) {
					$carDetails ["options"] [$o] = $o1;
				}
			}
		} else {
			if (mb_strpos ( $info, $_Lang->Text [$o] ) !== FALSE) {
				$carDetails ["options"] [$o] = 1;
			}
		}
	}
}
// сохранение в БД
function Car_Save(&$carDetails) {
	global $_MYSQL;
	// добавление записи о машине
	// формирование SQL
	$SQL_o = "`car-id`";
	$SQL_v = "NULL";
	foreach ( $carDetails ["car"] as $o => $v ) {
		$SQL_o .= ", `" . $o . "`";
		$SQL_v .= ", '" . $v . "'";
	}
	$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}cars` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
	if (! $_QUERY) {
		return FALSE;
	}
	$CAR_ID = $_MYSQL->LAST_ID ();
	// добавление записи о характеристиках
	if ($carDetails ["options"]) {
		// формирование SQL
		$SQL_o = "`o-id`";
		$SQL_v = "NULL";
		foreach ( $carDetails ["options"] as $o => $v ) {
			$SQL_o .= ", `" . $o . "`";
			$SQL_v .= ", '" . $v . "'";
		}
		$SQL_o .= ", `car-id`";
		$SQL_v .= ", '" . $CAR_ID . "'";
		$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-options` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
	}
	// добавление записи о цвете
	if ($carDetails ["colors"]) {
		// формирование SQL
		$SQL_o = "`c-id`";
		$SQL_v = "NULL";
		foreach ( $carDetails ["colors"] as $o => $v ) {
			$SQL_o .= ", `" . $o . "`";
			$SQL_v .= ", '" . $v . "'";
		}
		$SQL_o .= ", `car-id`";
		$SQL_v .= ", '" . $CAR_ID . "'";
		$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-colors` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
	}
	// добавление записи о топливе
	if ($carDetails ["fuel"]) {
		// формирование SQL
		$SQL_o = "`f-id`";
		$SQL_v = "NULL";
		foreach ( $carDetails ["fuel"] as $o => $v ) {
			$SQL_o .= ", `" . $o . "`";
			$SQL_v .= ", '" . $v . "'";
		}
		$SQL_o .= ", `car-id`";
		$SQL_v .= ", '" . $CAR_ID . "'";
		$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-fuels` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
	}
	// добавление записи о отделке
	if ($carDetails ["decors"]) {
		// формирование SQL
		$SQL_o = "`d-id`";
		$SQL_v = "NULL";
		foreach ( $carDetails ["decors"] as $o => $v ) {
			$SQL_o .= ", `" . $o . "`";
			$SQL_v .= ", '" . $v . "'";
		}
		$SQL_o .= ", `car-id`";
		$SQL_v .= ", '" . $CAR_ID . "'";
		$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-decors` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
	}
	// добавление записи о цене
	if ($carDetails ["price"]) {
		// формирование SQL
		$SQL_o = "`p-id`";
		$SQL_v = "NULL";
		foreach ( $carDetails ["price"] as $o => $v ) {
			$SQL_o .= ", `" . $o . "`";
			$SQL_v .= ", '" . $v . "'";
		}
		$SQL_o .= ", `car-id`";
		$SQL_v .= ", '" . $CAR_ID . "'";
		$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-price` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
	}
	// добавление записи о изображении
	if ($carDetails ["imgs"]) {
		foreach ( $carDetails ["imgs"] as $img ) {
			// формирование SQL
			$SQL_o = "`i-id`";
			$SQL_v = "NULL";
			foreach ( $img as $o => $v ) {
				$SQL_o .= ", `" . $o . "`";
				$SQL_v .= ", '" . $v . "'";
			}
			$SQL_o .= ", `car-id`";
			$SQL_v .= ", '" . $CAR_ID . "'";
			$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-images` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
		}
	}
	// дилеры
	if ($carDetails ["diler"]) {
		if ($carDetails ["diler"] ["di-href"] != "") {
			$_SELECT = $_MYSQL->SELECT ( "SELECT `d-id` FROM `{p}dialers` WHERE `di-href` = '" . $carDetails ["diler"] ["di-href"] . "'" );
		}
		if (! $_SELECT) {
			// формирование SQL
			$SQL_o = "`di-id`";
			$SQL_v = "NULL";
			foreach ( $carDetails ["diler"] as $o => $v ) {
				$SQL_o .= ", `" . $o . "`";
				$SQL_v .= ", '" . $v . "'";
			}
			$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}dialers` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
			$_SELECT ["di-id"] = $_MYSQL->LAST_ID ();
		}
		$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-dialer` (`cd-id`, `car-id`, `dialer-id`) VALUES (NULL, " . $CAR_ID . ", " . $_SELECT ["di-id"] . ")" );
	}
	// марка/модель
	$_MARKS = $_MYSQL->SELECT ( "SELECT `ma-id`, `ma-name` FROM `{p}marks`", MYSQL_SQUERY );
	while ( $mark = $_MYSQL->FETCH_Array ( $_MARKS ) ) {
		if ((mb_stripos ( $carDetails ["car"] ["car-name"], $mark ["ma-name"] ) === 0) || (mb_strpos ( $model ["ma-name"], "Другие" ) !== FALSE)) {
			$SQL_o = "`mm-id`, `mark-id`, `car-id`";
			$SQL_v = "NULL, " . $mark ["ma-id"] . ", " . $CAR_ID;
			$_MODELS = $_MYSQL->SELECT ( "SELECT `mo-id`, `mo-name` FROM `{p}models` WHERE `mark-id` = " . $mark ["ma-id"], MYSQL_SQUERY );
			$model_ID = 0;
			while ( $model = $_MYSQL->FETCH_Array ( $_MODELS ) ) {
				if ((mb_strpos ( $model ["mo-name"], "Другие" ) !== FALSE) && ($model_ID == 0)) {
					$model_ID = $model ["mo-id"];
				}
				if (mb_stripos ( $carDetails ["car"] ["car-name"], $mark ["ma-name"] . ' ' . $model ["mo-name"] ) !== FALSE) {
					$model_ID = $model ["mo-id"];
				}
			}
			if ($model_ID != 0) {
				$SQL_o .= ", `model-id`";
				$SQL_v .= ", " . $model_ID;
			}
			$_QUERY = $_MYSQL->QUERY ( "INSERT INTO `{p}car-markmodel` (" . $SQL_o . ") VALUES (" . $SQL_v . ")" );
			break;
		}
	}
	return TRUE;
}

function get_sec() {
	$mtime = microtime ();
	$mtime = explode ( " ", $mtime );
	$mtime = $mtime [1] + $mtime [0];
	return $mtime;
}
?>
